package com.cherry.androidcode.recyclerView

import com.cherry.androidcode.entity.HttpResult
import com.cherry.androidcode.entity.SearchBean
import com.cherry.androidcode.mvp1.MVPBasePresenter
import com.cherry.androidcode.okgo.BaseObserver
import com.cherry.androidcode.okgo.JsonConvert
import com.lzy.okgo.OkGo
import com.lzy.okrx2.adapter.ObservableBody
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers

/**
 * @author DongMS
 * @since 2019/7/15
 */
class TestSimpleRecyclerViewPresenter : TestSimpleRecyclerViewContract.Presenter, MVPBasePresenter<TestSimpleRecyclerViewContract.View>() {
    override fun reload(keyWord: String) {
        loadData(keyWord, 0, true)
    }

    override fun loadMore(page: Int, keyWord: String) {
        loadData(keyWord, page, false)
    }

    private fun loadData(keyWord: String, page: Int, isRefresh: Boolean) {
        val searchUrl = "https://www.wanandroid.com/article/query/$page/json"
        OkGo.post<HttpResult<SearchBean>>(searchUrl)
                .params("k", keyWord)
                .converter(object : JsonConvert<HttpResult<SearchBean>>() {})
                .adapt(ObservableBody<HttpResult<SearchBean>>())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : BaseObserver<SearchBean>(this) {

                    override fun onSuccess(data: SearchBean) {
                        view?.updateListSuccess(data.datas, isRefresh)
                    }

                    override fun onError(e: Throwable) {
                        view?.updateListFail(e.message ?: "", isRefresh)
                    }
                })
    }
}